package com.cn.shuangzi.userinfo;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import com.cn.shuangzi.userinfo.permission.RequestCameraPermissionHelper;
import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.permission.RequestPermissionViewP;
import com.cn.shuangzi.util.SZFileUtil;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.view.pop.FilterPop;
import com.cn.shuangzi.view.pop.common.CtrlItem;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.compress.CompressConfig;
import org.devio.takephoto.model.CropOptions;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.LubanOptions;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by CN.
 */

public abstract class BasePhotoActivity extends SZBaseActivity implements TakePhoto.TakeResultListener, InvokeListener, RequestPermissionViewP {

    private RequestCameraPermissionHelper requestCameraPermissionHelper;
    private File fileLuBan;
    private InvokeParam invokeParam;
    private TakePhoto takePhoto;

    private boolean isNeedCrop;
    private List<CtrlItem> ctrlItemList;

    public abstract void onTakePhotoSuccess(TResult result);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestCameraPermissionHelper = new RequestCameraPermissionHelper(this, this);
        setRequestPermissionHelper(requestCameraPermissionHelper);
    }

    public void showNormalPop(final boolean isNeedCrop, final boolean isNeedTitle, final boolean isNeedReset) {
        if (ctrlItemList == null) {
            ctrlItemList = new ArrayList<>();
            ctrlItemList.add(new CtrlItem(getString(R.string.txt_take_capture)));
            ctrlItemList.add(new CtrlItem(getString(R.string.txt_pick_from_gallery)));
        }
        showBottomCtrl(ctrlItemList, new FilterPop.OnItemClickListener() {
            @Override
            public void onItemChecked(int position, CtrlItem ctrlItem) {
                switch (position) {
                    case 0:
                        if (isNeedCrop) {
                            pickFromCaptureCrop();
                        } else {
                            pickFromCapture();
                        }
                        break;
                    case 1:
                        if (isNeedCrop) {
                            pickFromGalleryCrop();
                        } else {
                            pickFromGallery();
                        }
                        break;
                }
            }
        }, isNeedTitle ? getString(R.string.txt_select_pic) : null, isNeedReset);
    }

    @Override
    public void takeSuccess(final TResult result) {
        //这里不是主线程
        fileLuBan = new File(result.getImage().getCompressPath());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                onTakePhotoSuccess(result);
            }
        });
    }

    @Override
    public void takeFail(TResult result, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                SZToast.error(msg);
            }
        });
    }

    @Override
    public void takeCancel() {
    }

    public void pickFromGallery() {
        isNeedCrop = false;
        configCompress(getTakePhoto());
        getTakePhoto().onPickFromGallery();
    }

    public void pickFromGalleryCrop() {
        isNeedCrop = true;
        configCompress(getTakePhoto());
        final Uri imageUri = Uri.fromFile(SZFileUtil.getInstance().getOneTmpPic());
        getTakePhoto().onPickFromGalleryWithCrop(imageUri, getCropOptions());
    }

    public void pickFromCapture() {
        isNeedCrop = false;
        requestCameraPermissionHelper.checkPermissions();
    }

    public void pickFromCaptureCrop() {
        isNeedCrop = true;
        requestCameraPermissionHelper.checkPermissions();
    }

    public CropOptions getCropOptions() {
        return getCropOptions(true);
    }

    public CropOptions getCropOptions(boolean isAspect) {
        int height = 800;
        int width = 800;
        CropOptions.Builder builder = new CropOptions.Builder();
        if (isAspect) {
            builder.setAspectX(width).setAspectY(height);//按照比例拉伸
        } else {
            builder.setOutputX(width).setOutputY(height);//长宽 自由拉伸
        }
        builder.setWithOwnCrop(false);
        return builder.create();
    }

    public CropOptions getCropOptions(boolean isAspect, int height, int width) {
        CropOptions.Builder builder = new CropOptions.Builder();
        if (isAspect) {
            builder.setAspectX(width).setAspectY(height);//按照比例拉伸
        } else {
            builder.setOutputX(width).setOutputY(height);//长宽 自由拉伸
        }
        builder.setWithOwnCrop(false);
        return builder.create();
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public void onPermissionRequestSuccess(String[] permissionName) {
        for (String permission : permissionName) {
            if (Manifest.permission.CAMERA.equalsIgnoreCase(permission)) {
                configCompress(getTakePhoto());
                final Uri imageUri = Uri.fromFile(SZFileUtil.getInstance().getOneTmpPic());
                if (isNeedCrop) {
                    getTakePhoto().onPickFromCaptureWithCrop(imageUri, getCropOptions());
                } else {
                    getTakePhoto().onPickFromCapture(imageUri);
                }
            }
        }
    }

    @Override
    public void onRequestPermissionAlertCancelled(String permissionsNeed) {
    }

    private void configCompress(TakePhoto takePhoto) {
        LubanOptions option = new LubanOptions.Builder().setMaxSize(1024 * 200).create();
        CompressConfig config = CompressConfig.ofLuban(option);
        config.enablePixelCompress(false);
        takePhoto.onEnableCompress(config, true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            SZFileUtil.getInstance().clearTmpFiles();
        } catch (Exception e) {
        }
        try {
            if (fileLuBan != null && fileLuBan.getAbsolutePath().contains("luban_disk_cache")) {
                SZFileUtil.getInstance().clearFile(fileLuBan.getParentFile());
            }
        } catch (Exception e) {
        }
    }
}
